{% extends "base.html" %}
{% load static %}
{% load app_tags %}

{% block title %}
  Statistics - Yamtrack
{% endblock title %}

{% block content %}
  <div class="mb-8">
    <h1 class="text-3xl font-bold mb-2">Statistics</h1>
    <p class="text-gray-400">Track your media consumption habits</p>
  </div>
  <div x-data="dateRangePicker()" x-init="init()" class="relative mb-8">
    <!-- Trigger Button -->
    <button @click="toggleDropdown()"
            class="flex items-center gap-2 px-4 py-2.5 bg-[#2a2f35] hover:bg-[#343a40] rounded-lg transition-all duration-200 border border-gray-700 shadow-sm cursor-pointer">
      {% include "app/icons/calendar.svg" with classes="w-5 h-5 text-indigo-400" %}
      <span class="font-medium" x-text="selectedRange"></span>
      <div class="w-4 h-4 ml-1 transition-transform duration-200" :class="{'rotate-180': isOpen}">
        {% include "app/icons/chevron-down.svg" %}
      </div>
    </button>

    <!-- Dropdown -->
    <div x-cloak
         x-show="isOpen"
         x-transition
         @click.outside="isOpen = false"
         class="absolute z-20 mt-2 w-[340px] bg-[#2a2f35] rounded-lg shadow-lg border border-gray-700 overflow-hidden transition-all duration-200 animate-in fade-in-50 slide-in-from-top-5">

      <!-- Tabs -->
      <div class="flex border-b border-gray-700">
        <button @click="activeTab = 'predefined'"
                :class="{'text-white border-b-2 border-indigo-500': activeTab === 'predefined', 'text-gray-400 hover:text-gray-200': activeTab !== 'predefined'}"
                class="flex-1 py-3 text-sm font-medium transition-colors cursor-pointer">Predefined Ranges</button>
        <button @click="activeTab = 'custom'"
                :class="{'text-white border-b-2 border-indigo-500': activeTab === 'custom', 'text-gray-400 hover:text-gray-200': activeTab !== 'custom'}"
                class="flex-1 py-3 text-sm font-medium transition-colors cursor-pointer">Custom Range</button>
      </div>

      <!-- Predefined Ranges Tab -->
      <div x-show="activeTab === 'predefined'"
           class="p-2 max-h-80 overflow-y-auto">
        <div class="grid grid-cols-2 gap-2">
          <template x-for="range in predefinedRanges" :key="range.name">
            <button @click="selectPredefinedRange(range.name)"
                    :class="{'bg-indigo-600 text-white': selectedRange === range.name, 'hover:bg-[#39404b] text-gray-200': selectedRange !== range.name}"
                    class="flex items-center justify-between p-3 rounded-md text-left text-sm transition-all cursor-pointer">
              <span x-text="range.name"></span>
              <div x-show="selectedRange === range.name">
                {% include "app/icons/checkmark.svg" with classes="w-4 h-4" %}
              </div>
            </button>
          </template>
        </div>
      </div>

      <!-- Custom Range Tab -->
      <div x-show="activeTab === 'custom'" class="p-4">
        <div class="space-y-4">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-2 text-gray-300">Start Date</label>
              <input x-model="startDate"
                     @change="updateDateRange()"
                     class="w-full p-2.5 bg-[#39404b] rounded-md text-white border border-gray-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-sm scheme-dark"
                     type="date">
            </div>
            <div>
              <label class="block text-sm font-medium mb-2 text-gray-300">End Date</label>
              <input x-model="endDate"
                     @change="updateDateRange()"
                     class="w-full p-2.5 bg-[#39404b] rounded-md text-white border border-gray-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-sm scheme-dark"
                     type="date">
            </div>
          </div>

          <div class="flex items-center justify-center py-2 px-3 bg-[#343a40] rounded-md">
            <span class="text-sm text-gray-300" x-text="formatDisplayDate(startDate)"></span>
            {% include "app/icons/right-arrow.svg" with classes="mx-2 w-4 h-4 text-gray-500" %}
            <span class="text-sm text-gray-300" x-text="formatDisplayDate(endDate)"></span>
          </div>

          <div class="flex justify-end gap-2 pt-2">
            <button @click="isOpen = false"
                    class="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-gray-200 text-sm rounded-md transition-colors cursor-pointer">
              Cancel
            </button>
            <button @click="applyCustomRange()"
                    class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white text-sm rounded-md transition-colors cursor-pointer flex items-center gap-2">
              {% include "app/icons/checkmark.svg" with classes="w-4 h-4" %}
              Apply Range
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="space-y-8">
    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
      <div class="bg-[#2a2f35] rounded-lg p-6 flex items-center">
        <div class="bg-indigo-600/20 p-4 rounded-full mr-4">
          {% include "app/icons/states/completed.svg" with classes="w-8 h-8 text-indigo-400" %}
        </div>
        <div>
          <h3 class="text-sm font-medium text-gray-400">Completed Items</h3>
          {% if media_count.total %}
            <p class="text-2xl font-bold">
              {{ status_distribution.total_completed }} <span class="text-gray-500 text-lg">/ {{ media_count.total }}</span>
            </p>
          {% else %}
            <p class="text-2xl font-bold text-gray-500">--</p>
          {% endif %}
        </div>
      </div>
      <div class="bg-[#2a2f35] rounded-lg p-6 flex items-center">
        <div class="bg-yellow-600/20 p-4 rounded-full mr-4">
          {% include "app/icons/ribbon.svg" with classes="w-8 h-8 text-yellow-400" %}
        </div>
        <div>
          <h3 class="text-sm font-medium text-gray-400">Average Rating</h3>
          {% if score_distribution.total_scored %}
            <p class="text-2xl font-bold">
              {{ score_distribution.average_score }} <span class="text-gray-500 text-lg">/ 10</span>
            </p>
          {% else %}
            <p class="text-2xl font-bold text-gray-500">--</p>
          {% endif %}
        </div>
      </div>
      <div class="bg-[#2a2f35] rounded-lg p-6 flex items-center">
        <div class="bg-emerald-600/20 p-4 rounded-full mr-4">
          {% include "app/icons/calendar.svg" with classes="w-8 h-8 text-emerald-400" %}
        </div>
        <div>
          <h3 class="text-sm font-medium text-gray-400">Most Active Day</h3>
          {% if activity_data.stats.most_active_day %}
            <p class="text-2xl font-bold">{{ activity_data.stats.most_active_day }}</p>
            <p class="text-sm text-gray-500">{{ activity_data.stats.most_active_day_percentage }}% of activity</p>
          {% else %}
            <p class="text-2xl font-bold text-gray-500">--</p>
          {% endif %}
        </div>
      </div>
      <div class="bg-[#2a2f35] rounded-lg p-6 flex items-center">
        <div class="bg-red-600/20 p-4 rounded-full mr-4">
          {% include "app/icons/flame.svg" with classes="w-8 h-8 text-red-400" %}
        </div>
        <div>
          <h3 class="text-sm font-medium text-gray-400">Current Streak</h3>
          {% if activity_data.stats.most_active_day %}
            <p class="text-2xl font-bold">
              {{ activity_data.stats.current_streak }} day{{ activity_data.stats.current_streak|pluralize }}
              <p class="text-sm text-gray-500">
                Longest: {{ activity_data.stats.longest_streak }} day{{ activity_data.stats.longest_streak|pluralize }}
              </p>
            </p>
          {% else %}
            <p class="text-2xl font-bold text-gray-500">--</p>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- Activity History Section -->
    <div class="bg-[#2a2f35] rounded-lg p-6 max-w-[calc(100svw-4rem)]">
      <h2 class="text-xl font-semibold mb-4 text-center">Activity History</h2>
      <div class="overflow-x-auto flex flex-col justify-center"
           x-data="{ graphTooWide: false }"
           x-init="$nextTick(() => { const graphWidth = $refs.graphContainer.scrollWidth; const parentWidth = $el.clientWidth; graphTooWide = graphWidth > parentWidth; })"
           :class="graphTooWide ? 'items-start' : 'items-center'">

        <div class="p-4" x-ref="graphContainer">
          <!-- Months row -->
          <div class="flex mb-2 pl-[36.68px]">
            {% for month, week_count in activity_data.months %}
              <div class="text-xs text-gray-400"
                   style="width: calc({{ week_count }} * 1rem + ({{ week_count }} * 0.25rem))">{{ month }}</div>
            {% endfor %}
          </div>

          <!-- Graph wrapper -->
          <div class="flex">
            <!-- Weekday labels -->
            <div class="flex flex-col justify-between pr-2 text-sm text-gray-400">
              <div class="h-4 flex items-center">Mon</div>
              <div class="h-4"></div>
              <div class="h-4 flex items-center">Wed</div>
              <div class="h-4"></div>
              <div class="h-4 flex items-center">Fri</div>
              <div class="h-4"></div>
              <div class="h-4 flex items-center">Sun</div>
            </div>

            <!-- Weeks grid -->
            <div class="flex gap-1">
              {% for week in activity_data.calendar_weeks %}
                <div class="flex flex-col gap-1">
                  {% for day in week %}
                    <div class="w-4 h-4 rounded-sm transition-colors duration-200 hover:ring-2 hover:ring-white {% if day.level == 0 %}bg-[#2f353e]{% elif day.level == 1 %}bg-indigo-700{% elif day.level == 2 %}bg-indigo-600{% elif day.level == 3 %}bg-indigo-500{% elif day.level == 4 %}bg-indigo-400{% endif %}"
                         title="{{ day.date }}: {{ day.count }} activit{{ day.count|pluralize:"y,ies" }}"></div>
                  {% endfor %}
                </div>
              {% endfor %}
            </div>
          </div>
        </div>

        <!-- Legend -->
        <div class="flex items-center gap-2 pl-6 text-xs text-gray-400"
             :class="graphTooWide ? 'mb-5 mt-2' : 'mt-4'">
          <span>Less</span>
          <div class="w-4 h-4 rounded-sm bg-[#2f353e]"></div>
          <div class="w-4 h-4 rounded-sm bg-indigo-700"></div>
          <div class="w-4 h-4 rounded-sm bg-indigo-600"></div>
          <div class="w-4 h-4 rounded-sm bg-indigo-500"></div>
          <div class="w-4 h-4 rounded-sm bg-indigo-400"></div>
          <span>More</span>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
      <!-- Media Type Distribution Section -->
      <div class="bg-[#2a2f35] rounded-lg p-6">
        <h2 class="text-xl font-semibold mb-4">Media Type Distribution</h2>

        {% if media_type_distribution.labels %}
          <div class="h-80 flex justify-center items-center">
            <canvas id="mediaTypeChart"></canvas>
          </div>
        {% else %}
          <div class="flex flex-col items-center justify-center py-16">
            <div class="bg-[#39404b] rounded-full p-4 w-16 h-16 mx-auto mb-4 flex items-center justify-center">
              {% include "app/icons/piechart.svg" with classes="w-8 h-8 text-gray-400" %}
            </div>
            <h3 class="text-lg font-medium mb-2">No media types to display</h3>
            <p class="text-gray-400 text-center max-w-md">Add different types of media to see their distribution.</p>
          </div>
        {% endif %}
      </div>

      <!-- Status Distribution Section -->
      <div class="bg-[#2a2f35] rounded-lg p-6">
        <h2 class="text-xl font-semibold mb-4">Status Distribution</h2>

        {% if status_pie_chart_data.labels %}
          <div class="h-80 flex justify-center items-center">
            <canvas id="statusChart"></canvas>
          </div>
        {% else %}
          <div class="flex flex-col items-center justify-center py-16">
            <div class="bg-[#39404b] rounded-full p-4 w-16 h-16 mx-auto mb-4 flex items-center justify-center">
              {% include "app/icons/bars-increasing.svg" with classes="w-8 h-8 text-gray-400" %}
            </div>
            <h3 class="text-lg font-medium mb-2">No status data to display</h3>
            <p class="text-gray-400 text-center max-w-md">Track media items with different statuses to see their distribution.</p>
          </div>
        {% endif %}
      </div>

      <!-- Status Distribution by Media Type Section -->
      <div class="bg-[#2a2f35] rounded-lg p-6">
        <h2 class="text-xl font-semibold mb-4">Status Distribution by Media Type</h2>

        {% if media_type_distribution.labels %}
          <div class="h-80 flex justify-center items-center">
            <canvas id="statusStackedChart"></canvas>
          </div>
        {% else %}
          <div class="flex flex-col items-center justify-center py-16">
            <div class="bg-[#39404b] rounded-full p-4 w-16 h-16 mx-auto mb-4 flex items-center justify-center">
              {% include "app/icons/bars-pyramid.svg" with classes="w-8 h-8 text-gray-400" %}
            </div>
            <h3 class="text-lg font-medium mb-2">No data available</h3>
            <p class="text-gray-400 text-center max-w-md">
              Add media items with different statuses to see their distribution by type.
            </p>
          </div>
        {% endif %}
      </div>

      <!-- Score Distribution by Media Type Section -->
      <div class="bg-[#2a2f35] rounded-lg p-6">
        <h2 class="text-xl font-semibold mb-4">Score Distribution by Media Type</h2>

        {% if score_distribution.total_scored %}
          <div class="h-80 flex justify-center items-center">
            <canvas id="scoreStackedChart"></canvas>
          </div>
        {% else %}
          <div class="flex flex-col items-center justify-center py-16">
            <div class="bg-[#39404b] rounded-full p-4 w-16 h-16 mx-auto mb-4 flex items-center justify-center">
              {% include "app/icons/ribbon.svg" with classes="w-8 h-8 text-gray-400" %}
            </div>
            <h3 class="text-lg font-medium mb-2">No ratings yet</h3>
            <p class="text-gray-400 text-center max-w-md">Rate your media items to see score distribution statistics.</p>
          </div>
        {% endif %}
      </div>
    </div>

    <!-- Top Rated Media Section -->
    <div class="bg-[#2a2f35] rounded-lg p-6">
      <h2 class="text-xl font-semibold mb-4">Top Rated Media</h2>

      {% if top_rated %}
        <div class="media-grid">
          {% for media in top_rated %}
            {% include "app/components/media_card.html" with media=media item=media.item title=media.item from_grid=True secondary_color=True %}
          {% endfor %}
        </div>
      {% else %}
        <div class="flex flex-col items-center justify-center py-16">
          <div class="bg-[#39404b] rounded-full p-4 w-16 h-16 mx-auto mb-4 flex items-center justify-center">
            {% include "app/icons/ribbon.svg" with classes="w-8 h-8 text-gray-400" %}
          </div>
          <h3 class="text-lg font-medium mb-2">No ratings yet</h3>
          <p class="text-gray-400 text-center max-w-md">Rate your media items to see score distribution statistics.</p>
        </div>
      {% endif %}
    </div>

    <!-- Media Timeline Section -->
    <div class="bg-[#2a2f35] rounded-lg p-6 max-w-[calc(100svw-4rem)]">
      <h2 class="text-xl font-semibold mb-6 md:mb-10">Media Timeline</h2>

      {% if timeline %}
        <div class="relative flex justify-center">
          <div class="absolute top-0 bottom-0 w-px bg-indigo-500/50 hidden md:block"></div>

          <div class="w-full space-y-10 md:space-y-20">
            {% for month_year, media_list in timeline.items %}
              <div class="relative">

                <h3 class="text-lg font-medium text-center md:hidden md:text-left md:absolute md:top-0 md:left-1/2 md:transform md:translate-y-0 md:-translate-x-1/2 md:whitespace-nowrap">
                  {{ month_year }}
                </h3>

                <div class="absolute -top-6 left-1/2 transform -translate-x-1/2 z-10 hidden md:block">
                  <div class="w-3 h-3 rounded-full bg-indigo-500 mx-auto mb-2"></div>
                  <div class="absolute top-1.5 left-1/2 flex -translate-y-1/2">
                    {% if forloop.counter|divisibleby:2 %}
                      {# to the left #}
                      <div class="h-px w-40 bg-indigo-500/50 transform -translate-x-full"></div>
                      <div class="absolute -top-7 right-46 whitespace-nowrap">
                        <h3 class="text-lg font-medium">{{ month_year }}</h3>
                      </div>
                    {% else %}
                      {# to the right #}
                      <div class="h-px w-40 bg-indigo-500/50"></div>
                      <div class="absolute -top-7 left-4 whitespace-nowrap">
                        <h3 class="text-lg font-medium">{{ month_year }}</h3>
                      </div>
                    {% endif %}
                  </div>
                </div>
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4 md:w-[calc(50%-2rem)] lg:w-[calc(50%-1rem)] {% if forloop.counter|divisibleby:2 %}md:mr-auto md:ml-0{% else %}md:ml-auto md:mr-0{% endif %}">
                  {% for media in media_list %}
                    <div class="bg-[#39404b] p-4 rounded-lg hover:ring-2 hover:ring-indigo-500 transition-all duration-200">
                      <div class="flex items-start gap-4">
                        <div class="shrink-0 order-0">
                          <a href="{{ media.item|media_url }}">
                            <img alt="{{ media.item }}"
                                 class="lazyload w-16 h-24 rounded-md bg-[#3e454d] {% if media.item.image != IMG_NONE %}object-cover{% endif %} hover:opacity-80 transition-opacity"
                                 src="{{ IMG_NONE }}"
                                 data-src="{{ media.item.image }}">
                          </a>
                        </div>
                        <div class="flex-1 min-w-0">
                          <h4 class="font-medium">
                            <a href="{{ media.item|media_url }}"
                               class="hover:text-indigo-400 transition-colors line-clamp-2">{{ media.item }}</a>
                          </h4>
                          <div class="text-sm text-gray-400 mt-1">
                            <p>
                              {% if media.start_date %}{{ media.start_date|date_tracker_format }}{% endif %}
                              {% if media.start_date and media.end_date %}-{% endif %}
                              {% if media.end_date %}{{ media.end_date|date_tracker_format }}{% endif %}
                            </p>
                          </div>
                          {% if media.score is not None %}
                            <div class="flex items-center text-sm text-yellow-400 mt-2">
                              {% include "app/icons/star.svg" with classes="w-4 h-4 mr-1 fill-current" %}
                              <span>{{ media.formatted_score }}</span>
                            </div>
                          {% endif %}
                        </div>
                      </div>
                    </div>
                  {% endfor %}
                </div>
              </div>
            {% endfor %}
          </div>
        </div>
      {% else %}
        <div class="flex flex-col items-center justify-center py-16">
          <div class="bg-[#39404b] rounded-full p-4 w-16 h-16 mx-auto mb-4 flex items-center justify-center">
            {% include "app/icons/clock.svg" with classes="w-8 h-8 text-gray-400" %}
          </div>
          <h3 class="text-lg font-medium mb-2">Your timeline is empty</h3>
          <p class="text-gray-400 text-center max-w-md">Consume media items to see them appear on your timeline.</p>
        </div>
      {% endif %}
    </div>

  </div>
{% endblock content %}

{% block js %}
  <script src="{% static 'js/date-range.js' %}{% get_static_file_mtime 'js/date-range.js' %}"></script>

  <script src="{% static 'js/libraries/chartjs-4.4.9.min.js' %}"></script>
  <script src="{% static 'js/libraries/chartjs-datalabels-2.0.0.min.js' %}"></script>

  <!-- JSON data for charts -->
  {{ media_type_distribution|json_script:"media_type_distribution" }}
  {{ status_pie_chart_data|json_script:"status_pie_chart_data" }}
  {{ status_distribution|json_script:"status_distribution" }}
  {{ score_distribution|json_script:"score_distribution" }}

  <script src="{% static 'js/statistics-charts.js' %}{% get_static_file_mtime 'js/statistics-charts.js' %}"></script>
{% endblock js %}
